/*
 * @Author: OBKoro1
 * @Date: 2022-04-24 17:38:27
 * @LastEditors: shiguo
 * @LastEditTime: 2022-11-14 11:33:33
 * @FilePath: /@aks-dev/easyui/lib/MutiPictureView/MutiPictureView.tsx
 */

import * as React from 'react'
import { Image, View, StyleSheet, Keyboard, ImageSourcePropType, TouchableOpacity, MeasureOnSuccessCallback, Text } from 'react-native'
import { px2dp } from '../../screen/px2dp'
import { px2sp } from '../../screen/px2sp'

import SYImagePicker from "@aks-dev/react-native-syan-image-picker";


import type { MutiPictureViewProps } from '.'

let icon_add_image = require('./icon_add_image.png')
let icon_del_image = require('./icon_del_image.png')

const MutiPictureView: React.FC<MutiPictureViewProps> = (props) => {
    const {
        bind,
        maxCount = 6,
        type = 'showImagePicker',
        addIcon,
        addIconStyle,
        addIconContainerStyle,//borderWidth: 1, borderStyle: 'dashed', borderColor: assets.color_A3A9CC  虚线框
        itemContainerStyle,
        emptyPlaceHolderStyle,
        delIcon,
        delIconStyle,
        spacingHorizontal = px2dp(15),
        spacingInner = px2dp(8),
        editable = true,
        showEmptyPlaceHolder = false
    } = props
    const { viewModel, setViewModel } = bind
    React.useEffect(() => {


    }, [])

    const [sideLength, setSideLength] = React.useState<number>(0)



    const addPhoto = () => {
        let images: any[] = viewModel.photos || []
        if (!images) {
            throw new Error("viewModel没有定义photos字段")
        }

        if (type == 'showImagePicker') {
            SYImagePicker.showImagePicker({ imageCount: maxCount - (viewModel.photos?.length || 0), isCrop: false, isRecordSelected: false, quality: 20 }, (err, photos) => {
                if (!err) {
                    let imgs = photos.map((it) => { return { uri: it.uri } })
                    images = images.concat(imgs)
                    setViewModel({ photos: images })
                }
            })
        }

        if (type == 'openCamera') {
            SYImagePicker.openCamera({ imageCount: maxCount - (viewModel.photos?.length || 0), isCrop: false, isRecordSelected: false, quality: 20 }, (err, photos) => {
                if (!err) {
                    let imgs = photos.map((it) => { return { uri: it.uri } })
                    images = images.concat(imgs)
                    setViewModel({ photos: images })
                } else {
                    console.log('打开相机失败')
                }
            })
        }



    }

    const deletePhoto = (index: number) => {
        Keyboard.dismiss()
        let photos = [...viewModel.photos || []]
        photos.splice(index, 1)
        setViewModel({ photos: photos })
    }

    const showPhoto = (index: number) => {
        Keyboard.dismiss()
        let imgs: any[] = (props.value || viewModel.photos)?.filter((it) => { return (typeof it === 'string' && it.indexOf('http') >= 0) || typeof it == 'object' }) || []
        let images: any[] = []
        // console.log('viewModel', viewModel, imgs)
        imgs.forEach(it => {
            if (typeof it === 'string') {
                images.push({ uri: it })
            } else {
                images.push(it)
            }
        })
        setViewModel({
            imageViewer: {
                imageUrls: images.map((it) => {
                    return it.uri
                }),
                index: index,
                visible: true,
            }
        })
    }






    const ItemView: React.FC<{ source: ImageSourcePropType, index: number }> = ({ source, index }) => {

        return (
            <TouchableOpacity style={[styles.item_container, itemContainerStyle, {
                marginTop: index < 3 ? 0 : spacingInner,
                marginLeft: index % 3 == 0 ? spacingHorizontal : spacingInner,
                width: sideLength,
                height: sideLength,
            }]} activeOpacity={0.8} onPress={() => showPhoto(index)}>
                <Image source={source} style={{ width: '100%', height: '100%' }} resizeMode='cover' />
                {
                    editable && !props.value &&
                    <TouchableOpacity onPress={() => deletePhoto(index)} style={[styles.del_img_container, delIconStyle]}>
                        <Image source={delIcon ? delIcon : icon_del_image} resizeMode='contain' style={{ width: '100%', height: '100%' }} />
                    </TouchableOpacity>
                }
            </TouchableOpacity>
        )


    }



    const containerRef = React.useRef<{ measure: (callback: MeasureOnSuccessCallback) => void }>()

    React.useEffect(() => {
        containerRef.current?.measure((...args) => {
            // console.log('measure', args[2])
            if (args.length > 3) {
                let _sideLength = +((args[2] - spacingHorizontal * 2 - spacingInner * 2) / 3).toFixed(1);
                setSideLength(_sideLength - 0.1)
            }

        })
    })



    if (props.value && props.value?.length > 0) {
        return (
            <View style={[styles.container, props.style]} ref={containerRef as any}>
                {props.value instanceof Array && props.value?.map((item, index) => {
                    return <ItemView key={index} source={typeof item === 'string' ? { uri: item } : item} index={index} />
                })}

                {
                    showEmptyPlaceHolder && maxCount - (props.value?.length || 0) - 1 > 0 &&
                    Array.from({ length: maxCount - (props.value?.length || 0) - (editable ? 1 : 0) }, (_, k) =>
                        <View key={`sg-showEmptyPlaceHolder-${k}`} style={[styles.empty_place_container, emptyPlaceHolderStyle, itemContainerStyle, {
                            marginTop: k + (editable ? 1 : 0) + (props.value?.length || 0) > 2 ? spacingInner : 0,
                            marginLeft: (k + (editable ? 1 : 0) + (props.value?.length || 0)) % 3 == 0 ? spacingHorizontal : spacingInner,
                            width: sideLength,
                            height: sideLength,
                        }]} />
                    )
                }
            </View >
        )
    }

    return (
        <View style={[styles.container, props.style]} ref={containerRef as any}>
            {viewModel?.photos instanceof Array && viewModel.photos.map((item, index) => {
                return <ItemView key={index} source={typeof item === 'string' ? { uri: item } : item} index={index} />
            })}

            {
                !(viewModel?.photos?.length == maxCount) && editable && (
                    <TouchableOpacity style={[styles.item_container, itemContainerStyle, {
                        marginTop: (viewModel?.photos?.length || 0) >= 3 ? spacingInner : 0,
                        marginLeft: (viewModel?.photos?.length || 0) % 3 == 0 ? spacingHorizontal : spacingInner,
                        width: sideLength,
                        height: sideLength,
                    }, addIconContainerStyle]} activeOpacity={0.8} onPress={() => addPhoto()}>
                        <Image source={addIcon ? addIcon : icon_add_image} style={[{ width: '25%', height: '25%' }, addIconStyle]} resizeMode='contain' />
                        {props.addText && <Text style={[{ fontSize: px2sp(12), color: 'lightgrey', marginTop: px2dp(2) }, props.addTextStyle]}>{props.addText}</Text>}
                    </TouchableOpacity>

                )
            }
            {
                showEmptyPlaceHolder && maxCount - (viewModel.photos?.length || 0) - 1 > 0 &&
                Array.from({ length: maxCount - (viewModel.photos?.length || 0) - (editable ? 1 : 0) }, (_, k) =>
                    <View key={`sg-showEmptyPlaceHolder-${k}`} style={[styles.empty_place_container, emptyPlaceHolderStyle, itemContainerStyle, {
                        marginTop: k + (editable ? 1 : 0) + (viewModel.photos?.length || 0) > 2 ? spacingInner : 0,
                        marginLeft: (k + (editable ? 1 : 0) + (viewModel.photos?.length || 0)) % 3 == 0 ? spacingHorizontal : spacingInner,
                        width: sideLength,
                        height: sideLength,
                    }]} />
                )
            }
        </View >

    )
}








const styles = StyleSheet.create({
    container: {
        flex: 1,
        minHeight: 1,
        backgroundColor: 'transparent',
        display: 'flex',
        flexDirection: 'row',
        flexWrap: 'wrap',
        // borderRadius: px2dp(10),
    },
    item_container: {
        overflow: 'hidden',
        borderRadius: px2dp(10),
        display: 'flex',
        position: 'relative',
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#ededed',
    },

    del_img_container: {
        position: 'absolute',
        right: 2,
        top: 2,
        width: px2dp(24),
        height: px2dp(24)
    },
    empty_place_container: {
        borderRadius: px2dp(10),
        backgroundColor: '#ededed',
        borderColor: '#cccccc',
        borderWidth: .75,
    }
})


export default React.memo(MutiPictureView, (prevProps, nextProps) => false);



